<template>
  <div class="userRole">
    <div class="userRole-type">
      <div class="title">权限设置：</div>
      <div class="nav">
        <!-- <div class="nav_title">基础信息</div> -->
        <div class="list">
          <div v-for="(item, index) in treeList" :key="index">
            <div class="list_title">
              <el-checkbox
                :indeterminate="item.indeterminate"
                @change="(val) => handleCheckedAll(val, item)"
                v-model="item.checkAll"
              ></el-checkbox>
              {{ item.label }}
            </div>
            <!-- <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全部</el-checkbox> -->
            <!-- <el-checkbox-group v-model="idList[index]" @change="(val) => handleCheckedCitiesChange(item.children,idList[index],index)"> -->
            <el-checkbox
              v-for="(city, index) in item.children"
              :label="city.id"
              :key="index"
              @change="(val) => handleChecked(val, city)"
              v-model="menuIds"
              ><div class="label_show">{{ city.label }}</div></el-checkbox
            >
            <!-- </el-checkbox-group> -->
          </div>
        </div>
      </div>
    </div>
    <div style="padding-top: 20px; margin-left: 80px">
      <el-button
        plain
        @click="getPermission"
        >刷新</el-button
      >
      <el-button
        type="primary"
        :loading="saveLoading"
        @click="getCheckedKeys"
        >保存</el-button
      >
    </div>
  </div>
</template>

<script>
import API from "@/api/apiCompanyUser";
// import APICompany from "@/api/apiCompany";

export default {
  name: "CompanyDetail",
  props: {
    operationList: Array,
    typeId: Number,
    changeType: Number,
  },
  data() {
    return {
      checkAll: false,
      checkedCities: ["上海", "北京"],
      isIndeterminate: false,
      treeList: [],
      idList: [],
      saveLoading: false,

      menuIds: [], // 已选择的权限id
      checkAllIds: [], // 全选的菜单权限id
    };
  },
  watch: {
    typeId(val) {
      if (val) {
        this.fullscreenLoading = true;
        this.getPermission();
      }
    },
    changeType(val) {
      if (val) {
        this.fullscreenLoading = true;
        this.getPermission();
      }
    },
  },
  activated() {
    this.fullscreenLoading = true;
  },
  methods: {
    getCheckedKeys() {
      if (!this.menuIds || this.menuIds.length == 0) {
        this.$message({
          type: "warning",
          message: "请勾选权限",
        });
        return;
      }
      // let idList = this.idList
      //   .toString()
      //   .split(",")
      //   .map((item) => +item);
      const params = {
        token: this.$store.state.token,
        roleId: this.typeId,
        powerIds: this.menuIds.join(","),
      };
      this.saveLoading = true;
      API.upRolePermission(params).then((res) => {
        this.saveLoading = false;
        if (res.key === 1000) {
          this.permissionDialog = false;
          this.$message({
            type: "success",
            message: "分配成功",
          });
        }
      });
    },
    handleCheckedCitiesChange(value1, value2, index) {
      console.log(value1, value2);
      let type = true;
      value2.forEach((item) => {
        if (item == value1[0].id) {
          type = false;
        }
      });
      if (type) {
        let idList = this.idList;
        idList[index] = [];
        this.$set(this.idList, idList);
      }
    },
    getPermission() {
      this.roleId = this.typeId;
      this.idList = [];
      this.$bus.$emit("show-loading", true);
      const params = {
        token: this.$store.state.token,
        roleId: this.typeId,
      };
      API.getRolePermissionList(params).then((res) => {
        if (res.key === 1000) {
          res = res.result.list;
          this.permissionList = res;
          let treeList = [];
          const idList = [];
          const menuList = [];
          res.forEach((firstItem, index) => {
            // 判断是否全选
            let checkAllFlag = false;
            let hasOne = false;

            const firstObj = {
              // id: "x" + firstItem.id,
              id: firstItem.id,
              label: firstItem.powerName,
            };
            if (firstItem.list && firstItem.list.length > 0) {
              firstObj.children = [
                {
                  id: firstItem.id,
                  label: firstItem.powerName,
                },
              ];
              if (firstItem.isChoose === 1) {
                idList.push([firstItem.id]);
                menuList.push(firstItem.id);
                checkAllFlag = true;
                hasOne = true;
              } else {
                idList.push([]);
                checkAllFlag = false;
                hasOne = false;
              }
              let bol = true;
              firstItem.list &&
                firstItem.list.forEach((secondItem) => {
                  if (secondItem.buttonId) {
                    const secondObj = {
                      id: secondItem.buttonId,
                      label: secondItem.buttonName,
                    };
                    firstObj.children.push(secondObj);

                    if (secondItem.isChooseButton === 1) {
                      idList[index].push(secondItem.buttonId);
                      menuList.push(secondItem.buttonId);
                      hasOne = true;
                    } else if (secondItem.isChooseButton === 0) {
                      bol = false;
                      checkAllFlag = false;
                    }
                  }
                });
              if (bol) {
                idList[index].push(firstItem.id);
              }
            }

            if (checkAllFlag) {
              firstObj.checkAll = true;
              firstObj.indeterminate = false;
            } else {
              firstObj.checkAll = false;
              if (hasOne) {
                firstObj.indeterminate = true;
              } else {
                firstObj.indeterminate = false;
              }
            }

            treeList.push(firstObj);
          });
          this.treeList = treeList;
          let idList1 = [];
          idList.forEach((item) => {
            idList1.push(Array.from(new Set(item)));
          });
          this.idList = idList1;
          this.menuIds = Array.from(new Set(menuList));

          this.permissionDialog = true;
        }
        this.$bus.$emit("show-loading", false);
      });
    },
    handleChecked(val, row) {
      // 选中子菜单，要选中父菜单
      // 取消父菜单，要取消子菜单
      let currentId = row.id;
      let menuList = [];
      Object.assign(menuList, this.menuIds);
      if (val) {
        this.treeList.forEach((firstItem) => {
          // 选中子菜单，要选中父菜单
          firstItem.children.forEach((secondItem) => {
            if (secondItem.id === currentId) {
              menuList.push(firstItem.id);
            }
          });
        });
      } else {
        this.treeList.forEach((firstItem) => {
          if (firstItem.id == row.id) {
            if (firstItem.children) {
              firstItem.children.forEach((secondItem) => {
                if (menuList.includes(secondItem.id)) {
                  let index = menuList.indexOf(secondItem.id);
                  if (index > -1) {
                    menuList.splice(index, 1);
                  }
                }
              });
            }
          }
        });
      }
      this.menuIds = Array.from(new Set(menuList));

      // 修改全选状态
      this.treeList.forEach((firstItem) => {
        // 判断是否全选
        let checkAllFlag = false;
        let hasOne = false;

        if (this.menuIds.includes(firstItem.id)) {
          checkAllFlag = true;
          hasOne = true;
        } else {
          checkAllFlag = false;
          hasOne = false;
        }

        if (firstItem.children && firstItem.children.length > 0) {
          firstItem.children.forEach((secondItem) => {
            if (this.menuIds.includes(secondItem.id)) {
              hasOne = true;
            } else {
              checkAllFlag = false;
            }
          });
        }

        if (checkAllFlag) {
          firstItem.checkAll = true;
          firstItem.indeterminate = false;
        } else {
          firstItem.checkAll = false;
          if (hasOne) {
            firstItem.indeterminate = true;
          } else {
            firstItem.indeterminate = false;
          }
        }
      });
    },
    // 全选
    handleCheckedAll(val, row) {
      // 选中，菜单全选
      // 取消，菜单全部取消
      let currentId = row.id;
      let menuList = [];
      Object.assign(menuList, this.menuIds);
      if (val) {
        this.treeList.forEach((firstItem) => {
          if (firstItem.id == currentId) {
            firstItem.indeterminate = false;
            menuList.push(firstItem.id);
            if (firstItem.children) {
              firstItem.children.forEach((secondItem) => {
                menuList.push(secondItem.id);
              });
            }
          }
        });
      } else {
        this.treeList.forEach((firstItem) => {
          if (firstItem.id == currentId) {
            firstItem.indeterminate = false;
            let index = menuList.indexOf(firstItem.id);
            if (index > -1) {
              menuList.splice(index, 1);
            }

            if (firstItem.children) {
              firstItem.children.forEach((secondItem) => {
                if (menuList.includes(secondItem.id)) {
                  index = menuList.indexOf(secondItem.id);
                  if (index > -1) {
                    menuList.splice(index, 1);
                  }
                }
              });
            }
          }
        });
      }
      this.menuIds = Array.from(new Set(menuList));
    },
  },
};
</script>
<style>
.el-checkbox__label{
  width: 100%;
}
.label_show{
  width: 95%;
  white-space: normal;
  display: flex;
}
.list_title .el-checkbox{
  width: 10% !important;
}
</style>
<style lang="sass">
.userRole
  .el-checkbox-group
    display: flex
    flex-direction: column
  .el-checkbox
    margin-bottom: 18px
    width: 95%
</style>
<style lang="sass" scoped>
.userRole
  width: 100%
  height: 100%
  background: #FFFFFF
  box-shadow: 0px 0px 10px 0px rgba(93, 139, 198, 0.05)
  border-radius: 14px
  padding: 58px 73px
  margin-left: 0!important
  .userRole-type
    display: flex
    align-items: start
    justify-content: start
    .title
      font-size: 14px
      color: #222222
      line-height: 19px
    .nav
      width: calc(100% - 100px)
      height: 100%
      background: #FFFFFF
      border-radius: 11px
      border: 1px solid #E5E0E0
      padding: 30px 40px
      display: flex
      align-items: start
      .nav_title
        font-size: 16px
        font-weight: bold
        color: #222222
        line-height: 21px
        width: 100px
        flex: 0 0 auto
      .list
        display: flex
        flex-wrap: wrap
        >div
          width: 25%
          margin-bottom: 36px
          .list_title
            font-size: 14px
            color: #8E8E98
            line-height: 19px
            margin-bottom: 18px
</style>
